﻿using DryIoc;
using DryIoc.Microsoft.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Prism.DryIoc;
using Prism.Ioc;
using Prism.Modularity;
using Prism.Mvvm;
using System;
using System.IO;
using System.Net.Http;
using System.Reflection;
using System.Windows;
using TransformerManager.WPF.Common.Http;
using TransformerManager.WPF.Common.Http.Service;
using TransformerManager.WPF.Common.ViewModels;
using TransformerManager.WPF.Common.Views;
using TransformerManager.WPF.Main.ViewModels;
using TransformerManager.WPF.Main.Views;
using Container = DryIoc.Container;

namespace TransformerManager.WPF.Main
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : PrismApplication
    {
        public IConfiguration Configuration { get; private set; }
        public IServiceCollection Services { get; private set; }

        public App()
        {
            Services = new ServiceCollection();
            IConfigurationBuilder confignBuilder;
            string wpfEnv = Environment.GetEnvironmentVariable("WPF_ENVIRONMENT");
            if(wpfEnv == "Development")
            {
                confignBuilder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.Development.json", optional: false, true);
            }
            else
            {
                confignBuilder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: false, true);
            }

            Configuration = confignBuilder.Build();
        }

        protected override Window CreateShell()
        {
            return Container.Resolve<MainWindow>();
        }

        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {
            containerRegistry.RegisterForNavigation<ProjectInfoTemplate, ProjectInfoTemplateViewModel>();
            containerRegistry.RegisterForNavigation<DetailInfoTemplate, DetailInfoTemplateViewModel>();
            containerRegistry.RegisterForNavigation<ProjectListTemplate, ProjectListTemplateViewModel>();

            containerRegistry.RegisterForNavigation<BasicInfosTemplate, BasicInfosTemplateViewModel>();
            containerRegistry.RegisterForNavigation<TankInfoTemplate, TankInfoTemplateViewModel>();
            containerRegistry.RegisterForNavigation<ConservatorInfoTemplate, ConservatorInfoTemplateViewModel>();
            containerRegistry.RegisterForNavigation<CoolingSystemInfoTemplate, CoolingSystemInfoTemplateViewModel>();
            containerRegistry.RegisterForNavigation<AccessoriesInfoTemplate, AccessoriesInfoTemplateViewModel>();
            containerRegistry.RegisterForNavigation<LeadInfoTemplate, LeadInfoTemplateViewModel>();
            containerRegistry.RegisterForNavigation<WindingInfoTemplate, WindingInfoTemplateViewModel>();
            containerRegistry.RegisterForNavigation<ActivePartInfoTemplate, ActivePartInfoTemplateViewModel>();

            containerRegistry.RegisterDialog<UserListDialog, UserListDialogViewModel>("UserListDialog");
            containerRegistry.RegisterDialog<UserInfoDialog, UserInfoDialogViewModel>("UserInfoDialog");
            containerRegistry.RegisterDialog<ModifyPwdDialog, ModifyPwdDialogViewModel>("ModifyPwdDialog");
            containerRegistry.RegisterDialog<AboutDialog, AboutDialogViewModel>("AboutDialog"); 
            containerRegistry.RegisterDialog<RadiatorEditDialog, RadiatorEditDialogViewModel>("RadiatorEditDialog");
            containerRegistry.RegisterDialog<ReloadXmlDataOptionsDialog, ReloadXmlDataOptionsDialogViewModel>("ReloadXmlDataOptionsDialog");
        }

        protected override IContainerExtension CreateContainerExtension()
        {
            // 将初始化好的Configuration注入到容器服务中
            Services.AddSingleton<IConfiguration>(Configuration);

            Services.AddAutoMapper(Assembly.Load("TransformerManager.Shared"));

            Services.AddHttpClient<HttpRequest>(c =>
            {
                c.BaseAddress = new Uri(Configuration["Http:BaseUrl"]);
                c.DefaultRequestHeaders.Add("Accept", "application/json");
            }).ConfigurePrimaryHttpMessageHandler(() =>
            {
                return new HttpClientHandler()
                {
                    ServerCertificateCustomValidationCallback =
                    HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
                };
            });

            // 注入API请求服务
            Services.AddTransient<IAccountService, AccountService>();
            Services.AddTransient<IUserInfoService, UserInfoService>();
            Services.AddTransient<ITransformerService, TransformerService>();
            Services.AddTransient<IOperationLogService, OperationLogService>();

            return new DryIocContainerExtension(new Container(CreateContainerRules())
                .WithDependencyInjectionAdapter(Services));
        }

        protected override void ConfigureViewModelLocator()
        {
            base.ConfigureViewModelLocator();

            // xaml自动注册功能无效，这里手动注册下MainWindow和MainWindowViewModel的关系
            ViewModelLocationProvider.Register<MainWindow, MainWindowViewModel>();
            ViewModelLocationProvider.Register<AuthWindow, AuthWindowViewModel>();
        }

        protected override IModuleCatalog CreateModuleCatalog()
        {
            return new DirectoryModuleCatalog() { ModulePath = @".\Apps" };
        }

        protected override void InitializeShell(Window shell)
        {
            var authWindow = Container.Resolve<AuthWindow>();
            if (authWindow.ShowDialog() == true)
            {
                var shellVM = shell.DataContext as MainWindowViewModel;
                shellVM.InitData();
                base.InitializeShell(shell);
            }
            else
            {
                Application.Current.Shutdown(-1);
            }
        }
    }
}
